package com.darrenchan.leetcode;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2019-12-29 19:52
 */
public class Q35 {
    public int searchInsert(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int start = 0, end = nums.length - 1;
        while (start + 1 < end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] < target) {
                start = mid;
            } else {
                end = mid;
            }
        }


        if (nums[start] == target) {
            return start;
        }
        if (nums[end] == target) {
            return end;
        }

        if (target < nums[start]) {
            return start;
        } else if (target > nums[end]) {
            return end + 1;
        } else {
            return start + 1;
        }
    }


    public int searchInsert2(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int start = 0, end = nums.length - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] < target) {
                start = mid + 1;
            } else if(nums[mid] > target){
                end = mid - 1;
            } else {
                return mid;
            }
        }

        return start;
    }

    public static void main(String[] args) {
        System.out.println(new Q35().searchInsert(new int[]{1, 3, 5, 6}, 5));
    }
}
